package com.wangshaoyu.music_player.service;

import com.wangshaoyu.music_player.controller.StudioAlbumJsonController.AlbumView;
import com.wangshaoyu.music_player.data_object.AlbumDo;
import com.wangshaoyu.music_player.repository.AlbumRepo;
import com.wangshaoyu.music_player.repository.RelationRepo;
import com.wangshaoyu.music_player.session_object.UserSO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.wangshaoyu.music_player.repository.RelationRepo.*;

@Service
public class AlbumService {
    private final AlbumRepo albumRepo;
    private final RelationRepo relationRepo;

    @Autowired
    public AlbumService(AlbumRepo albumRepo, RelationRepo relationRepo) {
        this.albumRepo = albumRepo;
        this.relationRepo = relationRepo;
    }

    public List<AlbumView> list(UserSO currentUser) {
        List<AlbumDo> albumDoList = albumRepo.selectListByUid(currentUser.uid);
        if (albumDoList.isEmpty()) {
            return new ArrayList<>();
        }

        List<Integer> aidList = albumDoList.stream().map(AlbumDo::getAid).collect(Collectors.toList());
        List<AidToCountDo> aidToCountDoList = relationRepo.selectCountGroupByAidList(aidList);
        Map<Integer, Integer> aidToCountMap = new HashMap<>();
        for (AidToCountDo aidToCountDo : aidToCountDoList) {
            aidToCountMap.put(aidToCountDo.aid, aidToCountDo.count);
        }

        List<AlbumView> albumViewList = new ArrayList<>();
        for (AlbumDo albumDo : albumDoList) {
            AlbumView view = new AlbumView(albumDo);
            view.count = aidToCountMap.getOrDefault(albumDo.aid, 0);
            albumViewList.add(view);
        }

        return albumViewList;
    }
}
